package com.dems.remote.ali;


import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RefreshScope
public class SmsUtil {


    @Value("${ali.sms.accessKeyId}")
    private String ACCESS_KEY_ID;

    @Value("${ali.sms.accessKeySecret}")
    private String ACCESS_KEY_SECRET;

    public static final String ENDPOINT = "dysmsapi.aliyuncs.com";

    @Value("${ali.sms.signName}")
    public String SIGN_NAME;

    /**
     * 使用AK&SK初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public com.aliyun.dysmsapi20170525.Client createClient() throws Exception {

        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(ACCESS_KEY_ID)
                // 您的AccessKey Secret
                .setAccessKeySecret(ACCESS_KEY_SECRET);
        // 访问的域名
        config.endpoint = ENDPOINT;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public void doSendSms(String phoneNo, String templateCode, String param) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(SIGN_NAME)
                .setPhoneNumbers(phoneNo)
                .setTemplateCode(templateCode)
                .setTemplateParam(param);

        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse smsResponse = client.sendSms(sendSmsRequest);
        log.info("send sms req: {}, res: {}", JSON.toJSONString(sendSmsRequest), JSON.toJSONString(smsResponse));
    }

}
